﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Diagnostics.Contracts;

namespace DataStructure.Interview
{
    public class Question52
    {
        public static string PrintBinary(decimal numbers)
        {
            int intpart = (int)numbers;
            decimal decpart = numbers - intpart;

            StringBuilder intInBinary = new StringBuilder();
            StringBuilder decInBinary = new StringBuilder();


            while (intpart > 0)
            {
                int r = intpart % 2;
                intInBinary.Insert(0,r);
                intpart >>= 1;
            }

            while (decpart > 0)
            {
                if (decInBinary.Length > 32) break;
                if (decpart == 1)
                {
                    decInBinary.Append(1);
                    break;
                }

                decimal r = decpart * 2;
                if (r >= 1)
                {
                    decInBinary.Append(1);
                    decpart = r - 1;
                }
                else
                {
                    decInBinary.Append(0);
                    decpart = r;
                }
            }

            return intInBinary.ToString() + "." + decInBinary.ToString();
        }
    }
}

